<template>
  <div class="hold-transition">
    <div id="app" style="width: 85vw;">
      <div class="content-header">
        <h1>公告管理<small>公告信息</small></h1>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>公告管理</el-breadcrumb-item>
          <el-breadcrumb-item>公告信息</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div class="app-container">
        <div class="box">
          <!-- 搜索和操作按钮 -->
          <div class="filter-container">
            <el-input
                placeholder="标题/内容"
                v-model="pagination.queryString"
                style="width: 200px;"
                class="filter-item"
                @keyup.enter.native="handleFilter"
            ></el-input>
            <el-button @click="findPage" class="dalfBut">查询</el-button>
            <el-button type="primary" class="butT" @click="handleCreate">新建</el-button>
          </div>

          <!-- 数据表格 -->
          <el-table
              v-loading="loading"
              size="small"
              :data="dataList"
              stripe
              highlight-current-row
          >
            <el-table-column type="index" align="center" label="序号" />
            <el-table-column prop="title" label="标题" align="center" />
            <el-table-column prop="content" label="内容" align="center" />
            <el-table-column prop="publishDate" label="发布日期" align="center" />
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="handleDelete(scope.row.announcementsId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
                class="pagination"
                @current-change="findPage"
                :current-page="pagination.currentPage"
                :page-size="pagination.pageSize"
                layout="total, prev, pager, next, jumper"
                :total="pagination.total"
            />
          </div>

          <!-- 新建/编辑弹窗 -->
          <el-dialog title="公告操作" v-model="dialogFormVisible">
            <el-form :model="formData" :rules="formRules" label-width="100px" ref="formRef">
              <el-form-item label="标题" prop="title">
                <el-input v-model="formData.title" placeholder="请输入标题" />
              </el-form-item>
              <el-form-item label="内容" prop="content">
                <el-input type="textarea" v-model="formData.content" placeholder="请输入内容" />
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSave">确定</el-button>
            </div>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { reactive, toRefs, onMounted } from "vue";
import service from "@/util/http";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  setup() {
    const data = reactive({
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        queryString: "",
      },
      dataList: [],
      formData: {
        title: "",
        content: "",
        announcementsId: "", // 添加 announcementId 属性
      },
      dialogFormVisible: false,
      formRef: {},
      formRules: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        content: [{ required: true, message: "内容不能为空", trigger: "blur" }],
      },
    });

    const handleFilter = () => {
      // 根据输入的查询字符串进行过滤，这里只是示例，具体实现需要后端支持
      findPage();
    };

    const findPage = (page = 1) => {
      data.loading = true;
      data.pagination.currentPage = page;
      const params = {
        currentPage: data.pagination.currentPage,
        pageSize: data.pagination.pageSize,
        queryString: data.pagination.queryString,
      };
      service
          .get("/admin/announcement/findPage", { params })
          .then((response) => {
            const { records, total } = response.data.data;
            data.dataList = records;
            data.pagination.total = total;
            console.log("Updated dataList:", data.dataList); // 打印更新后的dataList
          })
          .finally(() => {
            data.loading = false;
          });
    };

    const handleCreate = () => {
      data.formData = { title: "", content: "", announcementsId: "" };
      data.dialogFormVisible = true;
    };

    const handleUpdate = (row) => {
      data.formData = {...row};
      data.dialogFormVisible = true;
      console.log("Updated formData:", data.formData); // 打印更新后的formData
    };

    const handleSave = () => {
      data.formRef.validate((valid) => {
        if (valid) {
          // 确定是更新还是新建操作
          const isUpdate = !!data.formData.announcementsId;
          const apiEndpoint = isUpdate
              ? `/admin/announcement/update/${data.formData.announcementsId}` // 更新接口
              : "/admin/announcement/add"; // 新建接口
          const method = isUpdate ? "put" : "post"; // 根据操作选择HTTP方法

          // 发送请求
          service[method](apiEndpoint, data.formData).then(() => {
            ElMessage.success(isUpdate ? "更新成功" : "创建成功");
            data.dialogFormVisible = false; // 关闭对话框
            findPage(); // 重新加载列表
          }).catch((error) => {
            // 处理错误情况
            ElMessage.error(isUpdate ? "更新失败" : "创建失败");
            console.error(error); // 打印错误详情，便于调试
          });
        } else {
          ElMessage.error("请填写完整信息");
        }
      });
    };

    const handleDelete = (announcementsId) => {
      ElMessageBox.confirm("确定要删除这条公告吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            service.delete(`/admin/announcement/${announcementsId}`).then(() => {
              ElMessage.success("删除成功");
              findPage();
            });
          })
          .catch(() => {
            ElMessage.info("已取消操作");
          });
    };

    onMounted(() => {
      findPage();
    });

    return {
      ...toRefs(data),
      handleFilter,
      findPage,
      handleCreate,
      handleUpdate,
      handleSave,
      handleDelete,
    };
  },
};
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>